package com.hjieli.config.security.provider;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjieli.entity.SysRoleInfo;
import com.hjieli.entity.SysUserInfo;
import com.hjieli.entity.SysUserXRole;
import com.hjieli.service.SysRoleInfoService;
import com.hjieli.service.SysUserInfoService;
import com.hjieli.service.SysUserXRoleService;

public class WeixinMpAuthenticationProvider implements AuthenticationProvider {

	@Autowired
	private SysUserInfoService sysUserInfoService;
	@Autowired
	private SysUserXRoleService sysUserXRoleService;
	@Autowired
	private SysRoleInfoService sysRoleInfoService;
	
	@Autowired
    private PasswordEncoder passwordEncoder;
	
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
        String password = (String) authentication.getCredentials();

        QueryWrapper<SysUserInfo> queryWrapper = new QueryWrapper<SysUserInfo>();
        queryWrapper.eq("account", username);
        queryWrapper.eq("is_enable", 1);
        SysUserInfo sysUserInfo = sysUserInfoService.getOne(queryWrapper);
        if(sysUserInfo == null) {
        	throw new BadCredentialsException("用户不存在");
        }else {
        	//判断密码是否正确
        	if(!passwordEncoder.matches(password, sysUserInfo.getWxPassword())) {
        		throw new BadCredentialsException("密码错误");
        	}
        }
        
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(username,
                authentication.getCredentials(), userGrantedAuthorities(sysUserInfo.getId()));
        result.setDetails(authentication.getDetails());
        return result;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		// TODO Auto-generated method stub
		return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
	}

    private Set<GrantedAuthority> userGrantedAuthorities(String userId) {
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        if (StringUtils.isEmpty(userId)) {
            return authorities;
        }
        QueryWrapper<SysUserXRole> queryWrapper = new QueryWrapper<SysUserXRole>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("is_enable", 1);
        
        List<SysUserXRole> sysUserXRoles = sysUserXRoleService.list(queryWrapper);
        
        String roleIds = "";
        for(int index = 0; index < sysUserXRoles.size(); index ++) {
        	if(index > 0) {
        		roleIds += ",";
        	}
        	roleIds += sysUserXRoles.get(index).getRoleId();
        }
        
        QueryWrapper<SysRoleInfo> roleInfoQueryWrapper = new QueryWrapper<SysRoleInfo>();
        roleInfoQueryWrapper.in("id", roleIds.split(","));
        roleInfoQueryWrapper.eq("is_enable", 1);
        
        List<SysRoleInfo> roles = sysRoleInfoService.list(roleInfoQueryWrapper);
        for(int index = 0; index < roles.size(); index ++) {
        	authorities.add(new SimpleGrantedAuthority(roles.get(index).getRoleTag()));
        }
        return authorities;
    }
}
